package com.lyc.mall.util;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class HttpUtils {
    /**
     * 该方法的使用条件是：仅当请求体中是文本数据时才可用
     *
     * @param request
     * @return
     */
    public static String getRequestBody(HttpServletRequest request) {
        ServletInputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        String requestBody = null;

        // 自行获取请求体中的字符串
        // 获取请求体
        try {
            inputStream = request.getInputStream();
            byteArrayOutputStream = new ByteArrayOutputStream();

            int length = 0;
            byte[] bytes = new byte[1024];
            while ((length = inputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, length);
            }
            requestBody = byteArrayOutputStream.toString("utf-8");
            // 关闭流
            byteArrayOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return requestBody;
    }

    /**
     * 获取请求URI中的方法名称
     * @param request
     */
    public static String getOperation(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String operation = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        return operation;
    }
}
